package com.chiaching.framwork.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * Spring上下文工具类
 * @author chiaching
 */
@Component
public class SpringContextUtil implements ApplicationContextAware, EnvironmentAware {

    private static ApplicationContext applicationContext;

    private static Environment environment;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    @Override
    public void setEnvironment(Environment environment) {
        SpringContextUtil.environment = environment;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static <T> T getBean(String name, Class<T> clz) {
        return applicationContext.getBean(name, clz);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T) applicationContext.getBean(name);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> clz) throws BeansException {
        return (T) applicationContext.getBean(clz);
    }

    public static boolean isProdProfile() {
        return "prod".equals(getProfile());
    }

    public static boolean isTestProfile() {
        return "test".equals(getProfile());
    }

    public static boolean isDevProfile() {
        return "dev".equals(getProfile());
    }

    public static String getProfile() {
        return getProperty("spring.profiles.active");
    }

    /**
     * @Description: 根据环境变量获取url前缀
     * @author: ZhangQiWei
     * @date: 2020/8/24 9:43
     */
    public static String getUrlPrefixByProfile() {
        String profile = SpringContextUtil.getProfile();
        String profilesActive = "";
        if (!SpringContextUtil.isProdProfile()) {
            profilesActive = profile + "-";
        }
        return profilesActive;
    }

    public static String getProperty(String key) {
        return environment.getProperty(key);
    }



    public static String getApplicationName() {
        return environment.getProperty("spring.application.name");
    }

    public static int getPort() {
        return environment.getProperty("server.port", Integer.class);
    }

}
